<script setup lang="ts">
import { PropType, watch, ref } from "vue";
import { ElForm, ElFormItem, FormInstance } from "element-plus";
import { arrFind2, clo, tree2arr } from "@/util";
const
  props = defineProps({
    modelValue: { type: Object as PropType<gt.sql.goodsType>, default: format.def.goodsType, },
    disabled: { type: Boolean, default: false }
  }),
  rules = ref({
    name: { required: true, message: "名称2-20个字符", trigger: "blur", min: 2, max: 20, }
  }),
  tree = ref<Tree<gt.sql.goodsType>>([]),
  opt = ref({
    expandTrigger: "hover",
    checkStrictly: true,
    emitPath: false,
    value: "id",
    label: "name"
  }),
  entity = ref<FormInstance>();
async function init() {
  const t = clo(await gd.goodsTypeTree);
  if (props.modelValue.id && !props.disabled) {
    const a = arrFind2(t, { id: props.modelValue.id });
    if (a) {
      tree2arr([a]).forEach(e => {
        e.disabled = true;
      });
    }
  }
  tree.value = t;
}
watch(() => props, init, { deep: true, immediate: true });
function changePid() {
  if (!props.modelValue.pid) {
    props.modelValue.pid = "";
  }
}
defineExpose({
  validate() {
    return new Promise<boolean>((resolve) => {
      if (entity.value) {
        entity.value.validate().then(resolve).catch(() => { resolve(false); });
      } else {
        resolve(false);
      }
    });
  },
  resetFields() { entity.value?.resetFields(); }
});
</script>
<template>
  <ElForm class="goodsType xw zb" ref="entity" :model="modelValue" :rules="rules" labelWidth="6em">
    <ElFormItem label="id" prop="id"><el-input v-model="modelValue.id" disabled placeholder="系统自动生成" /></ElFormItem>
    <ElFormItem label="创建时间" prop="createTime"><el-input
        :modelValue="modelValue.createTime ? modelValue._createTime : '系统自动生成'" disabled /></ElFormItem>
    <ElFormItem label="上级分组" prop="_goodsType.name"><el-input :modelValue="modelValue._goodsType?.name"
        placeholder="系统自动生成" disabled />
    </ElFormItem>
    <ElFormItem label="隶属分组" prop="pid"><el-cascader v-model="modelValue.pid" :options="tree" :props="opt"
        :disabled="disabled" clearable collapse-tags-tooltip placeholder="请选择上级" @change="changePid" />
    </ElFormItem>
    <ElFormItem label="名称" prop="name"><el-input v-model="modelValue.name" placeholder="请输入名称" :disabled="disabled" />
    </ElFormItem>
  </ElForm>
</template>
<style lang="scss" scoped>
.goodsType {
  position: relative;
  >:not(.wf) {
    width: 49%;
  }
}
</style>